package com.lmk.ms.common.net.tcp.server;

import com.lmk.ms.common.net.tcp.server.service.TcpServerService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP服务端
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2023/4/25
 */
@Slf4j
public class TcpServer {


    /** 监听端口 */
    private int port;

    private TcpServer(int port) {
        this.port = port;
    }

    /**
     * 构建监听服务
     * @param port
     * @return
     */
    public static TcpServer listen(int port){
        return new TcpServer(port);
    }

    public void run(TcpServerService ss){
        ServerSocket server = null;
        try {
            server = new ServerSocket(port);

            log.info("服务端启动完成，开始监听：{}", port);
            while (true){
                Socket socket = server.accept();// 等待客户连接
                log.debug("新客户端连接...");
                ss.handel(socket);
                log.debug("客户端连接已受理，继续监听新的请求");
            }
        } catch (IOException e) {
            log.error("服务端异常：", e);
        } finally {
            if(server != null){
                log.info("关闭服务端...");
                try {
                    server.close();
                } catch (IOException e) {
                    log.error("服务端关闭serverSocket异常：", e);
                }
            }
        }
        log.info("服务端退出");
    }
}
